﻿using System;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using Common.Entities;

namespace Infrastructure.Gateways.Vk
{
    public class VkLoginGateway : BaseLoginGateway, IVkLoginGateway
    {
        #region constants

        private const string InputElement = "input";
        private const string NameAttribute = "name";
        private const string AccessTokenKey = "http://api.vkontakte.ru/blank.html#access_token";

        #endregion

        public new void BuildGateway(AutoResetEvent resultEvent, GatewayDetails gatewayDetails)
        {
            base.BuildGateway(resultEvent, gatewayDetails);
        }

        protected override string GetAccessTokenFromUrl(string absoluteUri)
        {
            var token = HttpUtility.ParseQueryString(absoluteUri);
            return token.Get(AccessTokenKey);
        }

        protected override void SetValueForHtmlElement(string element, string attributeName, string value)
        {
            if (_ieBrowser.Document != null)
            {
                var elementCollection = _ieBrowser.Document.GetElementsByTagName(InputElement);
                foreach (HtmlElement el in elementCollection)
                {
                    if (el.GetAttribute(NameAttribute) == element)
                        el.SetAttribute(attributeName, value);
                }
            }
        }

        protected override void InvokeMember(string element, string member)
        {
            if (_ieBrowser.Document == null)
                return;
            var submitButtonElement = _ieBrowser.Document.GetElementById(element);

            if (submitButtonElement != null) 
                submitButtonElement.InvokeMember(member);
        }
    }
}
